//
//  FlutterOpenGlView.swift
//  flutter_test_opengl_plugin
//
//  Created by yuanxc on 2024/5/23.
//

import Foundation
import FlutterMacOS
import GLKit

class FlutterOpenGlView: NSView {
    private var viewId: Int64
    private var arguments: Any?
    private var message : FlutterBinaryMessenger

    private var channel: FlutterMethodChannel

    init(viewId: Int64, arguments: Any? = nil, message: FlutterBinaryMessenger) {
        self.viewId = viewId
        self.arguments = arguments
        self.message = message

        // 绑定方法监听
        channel = FlutterMethodChannel(name: "flutter_opengl_view_\(viewId)", binaryMessenger: message)
        super.init(frame: .zero)

        channel.setMethodCallHandler { [weak self] in
            guard let `self` = self else { return }
            self.onMethodCall(call: $0, result: $1)
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    var backgroundColor: NSColor = .blue // 默认背景颜色为白色

    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)

        backgroundColor.setFill()
        dirtyRect.fill()
    }

    func onMethodCall(call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "initGL":
            ready(call, result: result);
            break
        case "initGLNative":
            ready(call, result: result);
            break
        case "ready":
            ready(call, result: result);
            break
        case "stop":
            result(nil)
            break
        default:
            result(FlutterMethodNotImplemented);
        }
    }

    private func ready(_ call: FlutterMethodCall, result: @escaping FlutterResult) {

    }
}
